package net.sf.rose.spring;

import java.io.File;
import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import net.sf.rose.boot.BootStrap;
import net.sf.rose.boot.bean.StaticLocationBean;
import net.sf.rose.web.util.WebUtils;

/**
 * 
 * @author fengjian
 * Spring启动时执行顺序
 * 1、@SpringRegistryUtils
 * 2、@FileWebMvcConfigurerAdapter
 * 3、@ApplicationUtils
 * 此类负责：
 * 静态文件的访问路径
 */
@Configuration
public class FileWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		boolean hasWebapp = false;
		String name, path = null;
		String url = WebUtils.SERVER_URL;
		List<StaticLocationBean> list = BootStrap.getBootBean().getLocationList();
		for (StaticLocationBean bean : list) {
			if (bean.getFile() != null) {
				if (bean.getKey().equals("webapp")) {
					hasWebapp = true;
				}
				name = bean.getMapping();
				path = "file:" + bean.getFile().getAbsolutePath() + '/';
				registry.addResourceHandler(name).addResourceLocations(path);
				System.out.print("静态文件的路径是：" + path + "http访问地址是：" + url + name);
			}
		}
		if (!hasWebapp) {
			File file = BootStrap.getResourceFile("webapp");
			if (file.exists()) {
				path = "file:" + file.getAbsolutePath() + '/';
				registry.addResourceHandler("/**").addResourceLocations(path);
				System.out.print("静态文件的路径是：" + path + "http访问地址是：" + url + "/**");
			}
		}
		super.addResourceHandlers(registry);
		// file:D:/uploadFiles/
/*		String path = ApplicationUtils.getRootImagePath().toString();
		path = "file:" + path + '/';
		// 访问images文件夹中的fengjing.jpg图片的地址为http://localhost:8080/images/fengjing.jpg
		registry.addResourceHandler("/images/**").addResourceLocations(path);
		System.out.println("静态图片文件的存储路径是：" + path);
		System.out.println("访问方式是：http://localhost:8080/images/fengjing.jpg");
		super.addResourceHandlers(registry);*/
	}
}
